package com.icesoft.core.web.suppose.safehttp.service;

import com.icesoft.core.web.model.CryptoKeyPair;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.stereotype.Component;

@AllArgsConstructor
@Component
public class CryptoKeyPairService {
    @Getter
    private final ICryptoService cryptoService;
    @Getter
    private final ICryptoKeyPairRepository cryptoKeyPairRepository;

    public String privateDecrypt(String keyId, String data) {
        return cryptoService.privateDecrypt(getCryptoKeyPair(keyId).getPrivateKey(), data);
    }

    public String publicEncrypt(String keyId, String data) {
        return cryptoService.publicEncrypt(getCryptoKeyPair(keyId).getPublicKey(), data);
    }

    private CryptoKeyPair getCryptoKeyPair(String keyId) {
        CryptoKeyPair cryptoKeyPair = cryptoKeyPairRepository.findKey(keyId);
        if (cryptoKeyPair == null) {
            throw new IllegalArgumentException("keyId不存在：" + keyId);
        }
        return cryptoKeyPair;
    }

}
